package com.wiloon.zookeeper.watch.node;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

/*
 * Created by roy on 7/12/17;
 */
public class NodeCacheX {
    CuratorFramework client = null;
    String zookeeperConnectionString = "127.0.0.1:2181";
    private static final String PATH = "/example/nodeCache";

    public static void main(String[] args) {
        new NodeCacheX().exec();
    }

    public void exec() {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);

        client.start();
        client.create().creatingParentContainersIfNeeded();

        NodeCache cache = null;
        cache = new NodeCache(client, PATH);
        try {
            cache.start();

            NodeCache finalCache = cache;
            NodeCacheListener listener = new NodeCacheListener() {
                @Override
                public void nodeChanged() throws Exception {
                    if (finalCache.getCurrentData() != null)
                        System.out.println("Node changed: " + finalCache.getCurrentData().getPath() + ", value: " + new String(finalCache.getCurrentData().getData()));
                }
            };
            cache.getListenable().addListener(listener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
